import React, { Component } from 'react';
import { Form, Input, Modal, message, Upload, Icon } from 'antd';
import axios from 'axios';
import eventEmitter from '../utils/utils.js';
import './index.css';

const FormItem = Form.Item;
const TextArea = Input.TextArea;
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};
export default class ArticleModal extends Component {
  state = {
    visible: false,
    edit: false,
    detailInfo: {},
    fileList: [],
  }

  getDetail = (id) => {
    const res = axios.get(`http://localhost:8000/article/detail/${id}`);
    Promise.resolve(res).then(rtn => {
      const data = rtn.data || {};
      const itemInfo = data.detailItem || {};
      this.articleContent && this.articleContent.setFieldsValue({
        articleImg: itemInfo.articleImg || []
      });
      this.setState({
        detailInfo: itemInfo,
        fileList: itemInfo.articleImg || []
      })
    })
  }
  show = (records) => {
    this.records = records;
    this.setState({
      visible: true,
      edit: records ? true : false,
    }, () => {
      if (records) {
        this.getDetail(records._id);
      }
    })
  }
  modalCancel = () => {
    this.setState({
      visible: false,
      detailInfo: {},
      fileList: []
    }, () => {
      this.articleContent.resetFields();
    })
  }
  modalConfirm = () => {
    this.articleContent.validateFields((err, values) => {
      if (!err) {
        let res;
        const { fileList } = this.state;
        values.articleImg = fileList;
        if (this.records) {
          // 编辑操作
          values.id = this.records._id;
          res = axios.put('http://localhost:8000/article/add', values);
        } else {
          // 新增操作
          res = axios.post('http://localhost:8000/article/add', values);
        }
        Promise.resolve(res).then((rtn) => {
          const data = rtn.data || {};
          if (data && data.success) {
            message.success(data.msg);
            this.modalCancel();
            eventEmitter.emit('addArticle', this.records);
          }
        })
      }
    })
  }
  // 上传文件
  handleChange = ({ fileList }) => {
    const fileArr = fileList.map((item) => {
      return {
        uid: item.uid,
        name: item.name,
        url: item.thumbUrl,
        status: item.status
      }
    })
    this.setState({ fileList: fileArr });
  };
  beforeUpload = (file) => {
    const isJPG = file.type === 'image/jpeg';
    if (!isJPG) {
      message.error('上传文件格式仅为JPG格式');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('上传文件最多2M');
    }
    return isJPG && isLt2M;
  }
  normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  }
  render() {
    const { visible, detailInfo, fileList, edit } = this.state;
    return (
      <Modal
        visible={visible}
        width={600}
        title={edit ? '编辑文章' : '添加文章'}
        okText="确定"
        cancelText="取消"
        onCancel={this.modalCancel}
        onOk={this.modalConfirm}
      >
        <ArticleContent
          ref={r => this.articleContent = r}
          detailInfo={detailInfo}
          fileList={fileList}
          handleChange={this.handleChange.bind(this)}
          beforeUpload={this.beforeUpload.bind(this)}
          normFile={this.normFile.bind(this)}
        />
      </Modal>
    )
  }
}
const ArticleForm = (props) => {
  const { detailInfo, fileList, handleChange, beforeUpload, normFile } = props;
  const { getFieldDecorator } = props.form;
  const uploadButton = (
    <div>
      <Icon type="plus" />
      <div className="ant-upload-text">上传配图</div>
    </div>
  );
  return (
    <Form encType="multipart/form-data" >
      <FormItem
        label="文章标题"
        {...formItemLayout}
      >
        {getFieldDecorator('title', {
          rules: [{
            required: true,
            message: '请输入文章标题'
          }],
          initialValue: detailInfo.title
        })(
          <Input placeholder="请输入文章标题" />
        )}
      </FormItem>
      <FormItem
        label="文章描述"
        {...formItemLayout}
      >
        {getFieldDecorator('desc', {
          rules: [{
            required: true,
            message: '请输入文章描述'
          }],
          initialValue: detailInfo.desc
        })(
          <TextArea placeholder="请输入文章描述" autosize={{ minRows: 4, maxRows: 8 }} />
        )}
      </FormItem>
      <FormItem
        label="文章内容"
        {...formItemLayout}
      >
        {getFieldDecorator('content', {
          rules: [{
            required: true,
            message: '请输入文章内容'
          }],
          initialValue: detailInfo.content
        })(
          <TextArea placeholder="请输入文章内容" autosize={{ minRows: 4, maxRows: 8 }} />
        )}
      </FormItem>
      <FormItem
        label="文章配图"
        {...formItemLayout}
      >
        {getFieldDecorator('articleImg', {
          rules: [{
            required: true,
            message: '请上传文章配图'
          }],
          valuePropName: 'fileList',
          getValueFromEvent: normFile,
        })(
          <Upload
            listType="picture-card"
            action="http://localhost:8000/article/upload"
            beforeUpload={beforeUpload}
            onChange={handleChange}
          >
            {fileList.length >= 1 ? null : uploadButton}
          </Upload>
        )}
      </FormItem>
    </Form>
  )
}
const ArticleContent = Form.create()(ArticleForm);
